<template>
  <div class="user-management-container">
    <div class="page-header">
      <h2>用户权限管理</h2>
    </div>
    
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadUsers">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="user-table-card">
      <el-table v-loading="loading" :data="userList" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="mobile" label="手机" width="120" />
        <el-table-column prop="roles" label="角色" width="120">
          <template #default="scope">
            <el-tag v-for="role in scope.row.roles" :key="role" class="mr-5">{{ getRoleLabel(role) }}</el-tag>
            <span v-if="!scope.row.roles || scope.row.roles.length === 0">-</span>
          </template>
        </el-table-column>
        <el-table-column label="权限" width="180">
          <template #default="scope">
            <el-tooltip 
              v-if="scope.row.permissions && scope.row.permissions.length > 0"
              :content="formatPermissionList(scope.row.permissions)" 
              placement="top"
            >
              <div class="permissions-preview">
                <el-tag 
                  v-for="perm in scope.row.permissions.slice(0, 2)" 
                  :key="perm" 
                  type="success" 
                  class="mr-5"
                >
                  {{ getPermissionLabel(perm) }}
                </el-tag>
                <el-tag v-if="scope.row.permissions.length > 2" type="info">+{{ scope.row.permissions.length - 2 }}</el-tag>
              </div>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="openPermissionDialog(scope.row)"
            >
              授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 权限编辑对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="编辑用户权限"
      width="600px"
    >
      <div v-if="currentUser">
        <h3>用户: {{ currentUser.username }}</h3>
        
        <div class="permissions-section">
          <h4>知识图谱分析权限</h4>
          <el-divider />
          
          <el-checkbox v-model="editPermissions['graph:view']" :disabled="hasAnyAnalysisPermission">
            {{ getPermissionLabel('graph:view') }}
          </el-checkbox>
          <div v-if="editPermissions['graph:view']" class="permission-note">
            <el-alert type="info" :closable="false" show-icon>
              勾选任何分析功能权限时会自动授予基础权限
            </el-alert>
          </div>
          
          <h4 class="mt-15">分析功能权限</h4>
          <el-checkbox-group v-model="selectedAnalysisPermissions" @change="handleAnalysisPermissionChange">
            <el-checkbox label="analysis:supply-chain">{{ getPermissionLabel('analysis:supply-chain') }}</el-checkbox>
            <el-checkbox label="analysis:industry-chain">{{ getPermissionLabel('analysis:industry-chain') }}</el-checkbox>
            <el-checkbox label="analysis:company-risk">{{ getPermissionLabel('analysis:company-risk') }}</el-checkbox>
            <el-checkbox label="analysis:high-tech">{{ getPermissionLabel('analysis:high-tech') }}</el-checkbox>
            <el-checkbox label="analysis:product-chain">{{ getPermissionLabel('analysis:product-chain') }}</el-checkbox>
            <el-checkbox label="analysis:company-stats">{{ getPermissionLabel('analysis:company-stats') }}</el-checkbox>
          </el-checkbox-group>
          
          <h4 class="mt-15">系统管理权限</h4>
          <el-divider />
          
          <h5>用户管理</h5>
          <el-checkbox-group v-model="selectedUserManagePermissions">
            <el-checkbox label="user:list">{{ getPermissionLabel('user:list') }}</el-checkbox>
            <el-checkbox label="user:view">{{ getPermissionLabel('user:view') }}</el-checkbox>
            <el-checkbox label="user:add">{{ getPermissionLabel('user:add') }}</el-checkbox>
            <el-checkbox label="user:edit">{{ getPermissionLabel('user:edit') }}</el-checkbox>
            <el-checkbox label="user:delete">{{ getPermissionLabel('user:delete') }}</el-checkbox>
            <el-checkbox 
              label="user:manage" 
              :disabled="currentUser.username === 'admin'"
            >
              {{ getPermissionLabel('user:manage') }}
            </el-checkbox>
          </el-checkbox-group>
          
          <h5 class="mt-15">角色管理</h5>
          <el-checkbox-group v-model="selectedRoleManagePermissions">
            <el-checkbox label="role:list">{{ getPermissionLabel('role:list') }}</el-checkbox>
            <el-checkbox label="role:view">{{ getPermissionLabel('role:view') }}</el-checkbox>
            <el-checkbox label="role:add">{{ getPermissionLabel('role:add') }}</el-checkbox>
            <el-checkbox label="role:edit">{{ getPermissionLabel('role:edit') }}</el-checkbox>
            <el-checkbox label="role:delete">{{ getPermissionLabel('role:delete') }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="savePermissions" 
            :disabled="isAdminRestricted"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 使用定义式导入，而不是解构导入，避免可能的编译问题
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import adminAPI from '@/api/admin';
import { useStore } from 'vuex';
import permissionUtils from '@/utils/permissionLabels';

export default {
  name: 'UserManagement',
  setup() {
    // 添加store引用
    const store = useStore();

    // 用户列表数据
    const userList = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    
    // 搜索表单
    const searchForm = reactive({
      username: ''
    });
    
    // 权限编辑对话框
    const permissionDialogVisible = ref(false);
    const currentUser = ref(null);
    const editPermissions = reactive({
      'graph:view': false
    });
    const selectedAnalysisPermissions = ref([]);
    const selectedUserManagePermissions = ref([]);
    const selectedRoleManagePermissions = ref([]);
    
    // 计算用户最终的权限列表
    const finalPermissions = computed(() => {
      const permissions = [];
      
      // 添加基本权限
      Object.keys(editPermissions).forEach(key => {
        if (editPermissions[key]) {
          permissions.push(key);
        }
      });
      
      // 添加分析权限
      permissions.push(...selectedAnalysisPermissions.value);
      
      // 添加用户管理权限
      permissions.push(...selectedUserManagePermissions.value);
      
      // 添加角色管理权限
      permissions.push(...selectedRoleManagePermissions.value);
      
      return permissions;
    });
    
    // 检查是否有任何分析权限被选中
    const hasAnyAnalysisPermission = computed(() => {
      return selectedAnalysisPermissions.value.length > 0;
    });
    
    // 检查是否限制修改admin权限
    const isAdminRestricted = computed(() => {
      if (!currentUser.value) return false;
      
      // 如果是admin用户且当前登录用户不是admin
      if (currentUser.value.username === 'admin') {
        const currentUserInfo = store.getters.userInfo;
        return currentUserInfo && currentUserInfo.username !== 'admin';
      }
      
      return false;
    });
    
    // 处理分析权限变化
    const handleAnalysisPermissionChange = (permissions) => {
      // 如果选中了任何分析权限，自动勾选基础权限
      if (permissions.length > 0) {
        editPermissions['graph:view'] = true;
      }
    };
    
    // 加载用户列表
    const loadUsers = async () => {
      loading.value = true;
      try {
        const params = {
          page: currentPage.value - 1,
          size: pageSize.value,
          username: searchForm.username
        };
        
        // 使用adminAPI对象调用
        const response = await adminAPI.getUsers(params);
        
        userList.value = response.content || [];
        total.value = response.totalElements || 0;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        ElMessage.error('获取用户列表失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 重置搜索条件
    const resetSearch = () => {
      searchForm.username = '';
      loadUsers();
    };
    
    // 处理分页
    const handleSizeChange = (size) => {
      pageSize.value = size;
      loadUsers();
    };
    
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      loadUsers();
    };
    
    // 打开权限编辑对话框
    const openPermissionDialog = (user) => {
      currentUser.value = { ...user };
      
      // 如果是admin用户且当前登录用户不是admin，则显示警告
      if (user.username === 'admin') {
        const currentUserInfo = store.getters.userInfo;
        if (currentUserInfo && currentUserInfo.username !== 'admin') {
          ElMessage.warning('注意：普通用户无法修改管理员权限');
        }
      }
      
      // 重置编辑状态
      Object.keys(editPermissions).forEach(key => {
        editPermissions[key] = user.permissions?.includes(key) || false;
      });
      
      // 设置选中的分析权限
      selectedAnalysisPermissions.value = user.permissions?.filter(p => p.startsWith('analysis:')) || [];
      
      // 设置选中的用户管理权限
      selectedUserManagePermissions.value = user.permissions?.filter(p => p.startsWith('user:')) || [];
      
      // 设置选中的角色管理权限
      selectedRoleManagePermissions.value = user.permissions?.filter(p => p.startsWith('role:')) || [];
      
      permissionDialogVisible.value = true;
    };
    
    // 保存权限设置
    const savePermissions = async () => {
      try {
        // 使用adminAPI对象调用
        await adminAPI.updateUserPermissions(currentUser.value.id, {
          permissions: finalPermissions.value
        });
        
        ElMessage.success('权限设置已保存');
        permissionDialogVisible.value = false;
        
        // 如果修改的是当前登录用户的权限，强制刷新用户信息
        const currentUserInfo = store.getters.userInfo;
        if (currentUserInfo && currentUserInfo.id === currentUser.value.id) {
          try {
            await store.dispatch('getUserInfo', true);
            console.log('用户权限已更新，已强制刷新用户信息');
          } catch (error) {
            console.error('刷新用户信息失败:', error);
          }
        }
        
        loadUsers(); // 重新加载用户列表
      } catch (error) {
        console.error('保存权限设置失败:', error);
        
        // 显示详细的错误信息
        if (error.data) {
          // 直接使用error.data (由request.js添加)
          if (error.data.message) {
            ElMessage.error(error.data.message);
            return;
          }
        } else if (error.response && error.response.data) {
          // 兼容处理
          const errorData = error.response.data;
          if (errorData.message) {
            ElMessage.error(errorData.message);
            return;
          }
        }
        
        // 如果没有具体错误信息，则显示通用错误
        ElMessage.error('保存权限设置失败');
      }
    };
    
    // 格式化权限列表为友好的字符串
    const formatPermissionList = (permissions) => {
      if (!permissions || permissions.length === 0) return '-';
      return permissions.map(perm => permissionUtils.getPermissionLabel(perm)).join(', ');
    };

    // 从permissionUtils导入函数
    const getPermissionLabel = (permission) => {
      return permissionUtils.getPermissionLabel(permission);
    };

    const getRoleLabel = (role) => {
      return permissionUtils.getRoleLabel(role);
    };
    
    // 页面加载时获取用户列表
    onMounted(() => {
      loadUsers();
    });
    
    return {
      userList,
      loading,
      currentPage,
      pageSize,
      total,
      searchForm,
      permissionDialogVisible,
      currentUser,
      editPermissions,
      selectedAnalysisPermissions,
      selectedUserManagePermissions,
      selectedRoleManagePermissions,
      loadUsers,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      openPermissionDialog,
      savePermissions,
      hasAnyAnalysisPermission,
      handleAnalysisPermissionChange,
      isAdminRestricted,
      getPermissionLabel,
      getRoleLabel,
      formatPermissionList
    };
  }
};
</script>

<style scoped>
.user-management-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.user-table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.permissions-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-divider {
  margin: 12px 0;
}

.permissions-section {
  margin-top: 15px;
}

.permissions-section h4 {
  margin: 12px 0 8px 0;
  font-size: 16px;
  color: #303133;
}

.permissions-section h5 {
  margin: 10px 0 8px 0;
  font-size: 14px;
  color: #606266;
}

.permission-note {
  margin: 8px 0;
  font-size: 13px;
}

.mt-15 {
  margin-top: 15px;
}

.mr-5 {
  margin-right: 5px;
}
</style> 